package com.um.jdy.ykc.netty;

import cn.hutool.json.JSONUtil;
import com.um.jdy.common.device.entity.po.EvLog;
import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.service.EvLogService;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.ykc.command.YkcCommand;
import com.um.jdy.ykc.properties.HshNettyProperties;
import com.um.jdy.ykc.utils.RadixsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 甘天伟
 * @since 2024/7/31
 * 版权所有 广州优匠科技有限公司
 */
@Component
public class CommandLogs {

    @Autowired
    HshNettyProperties hshNettyProperties;

    @Lazy
    @Autowired
    PileService pileService;

    @Autowired
    EvLogService evLogService;

    @Async
    public void addLogs(String imei, YkcCommand command) {
        if (!hshNettyProperties.isWriteLog()) return;

        EvLog entity = new EvLog();

        Pile devicePile = pileService.getEntity("imei", imei);

        entity.setComId(devicePile == null ? "" : devicePile.getComId());
        entity.setCode(devicePile == null ? "" : devicePile.getCode());
        entity.setImei(imei);
        entity.setBeginField(command.getBeginField() + "");
        entity.setLength(command.getLength() + "");
        entity.setSerial(command.getSerial() + "");
        entity.setEncFlag(command.getEncFlag() + "");
        entity.setCommand(command.getCommand() + "");
        entity.setData(RadixsUtil.bytesToHexString(command.getData()));
        entity.setVerify(command.getVerify() + "");
        entity.setBytes(RadixsUtil.bytesToHexString(command.toBytes()));
        entity.setJson(JSONUtil.toJsonStr(command));
        entity.setCreateTime(new Date());

        evLogService.save(entity);
    }
}
